package com.BMS.DAOImpl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.stereotype.Repository;

import com.BMS.DAO.BorrowDao;
import com.BMS.entity.Book;
import com.BMS.entity.Borrow;
/**
 * 图书借阅DAO层实现类
 * @author lenovo
 *
 */
@Repository("BorrowDaoImpl")
public class BorrowDaoImpl implements BorrowDao {

	@Resource
	private SessionFactory sessionFactory;
	
	private Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	
	@Override
	public void addBorrow(Borrow borrow) {
		String sql = "SELECT borrowBook(?,?,?,?)";
		SQLQuery q = this.getSession().createSQLQuery(sql);
		q.setString(0, borrow.getReader_ID());
		q.setString(1, borrow.getManager_ID());
		q.setString(2, borrow.getBook_ID());
		q.setDate(3, borrow.getBorrow_date());
		List list = q.list();
	}

	@Override
	public void deleteBorrowById(int borrow_id) {
		this.getSession().createQuery("delete Borrow where borrow_ID=?").setParameter(0, borrow_id).executeUpdate();
	}

	@Override
	public Borrow findBorrowById(int borrow_id) {
		return (Borrow) this.getSession().createQuery("from Borrow where borrow_ID=?").setParameter(0, borrow_id).uniqueResult();
	}
	
	@Override
	public Borrow findBorrowByBookId(String book_id) {
		return (Borrow) this.getSession().createQuery("from Borrow borrow where book_ID=? order by borrow.borrow_date desc").setParameter(0, book_id).setFirstResult(0).setMaxResults(1).uniqueResult();
	}

	@Override
	public void updateBorrow(Borrow borrow) {
		this.getSession().update(borrow);
	}

	// 获取图书借阅状态
	public boolean isBorrowable(String book_id) {
		String sql = "select * from borrowable_book_list where book_ID="+book_id;
		SQLQuery q = this.getSession().createSQLQuery(sql)
				.addScalar("book_ID", StandardBasicTypes.STRING);
		List list = q.list();
		if(list.size()==0) {
			return false;
		} else {
			return true;
		}
	}
}
